﻿/// <reference path="../core/jquery-1.4.2.min-vsdoc.js"/>
/// <reference path="../config/sw-config-default.js"/>
/// <reference path="../core/sw-prototype.js"/>
/// <reference path="../core/sw.js"/>
/// <reference path="../core/sw-control-core.js"/>

/***************************************************************************
jQuery vaildator
NOTE: Created for SmartUI. 
Copyright 2010, Roy zhang
Features：
1.基于input进行非空、格式、范围验证，分组验证
2.支持扩展控件chooser的非空、选择范围验证
3.系统默认配置规则验证
4.自定义规则(正则表达式)，自定义方法验证
Update Note：

Needs：
****************************************************************************/
(function ($) {
    $.fn.initValid = function (options) {
        /// <summary>pager</summary>
        /// <param name="options" type="Array">配置项</param>

        ///#region 主体内容
        return this.each(function () {
            var ctr = $(this);
            var ctrtype = ctr.attr("ctr");
            if (ctrtype) {//自定义控件验证
                var id = ctr.attr('id');
                ctr.attr("ctr", ctrtype);
                switch (ctrtype) {
                    case 'ddl': //下拉选择菜单
                        $('#' + id + "_1").addClass("valid").blur(function () {
                            var ctr = $(this);
                            valid($('#' + ctr.attr("id").substring(0, ctrid.length - 2)), ctr);
                        });
                        break;
                    case 'list': //选择list
                        $('#' + id + "_chooser").addClass("valid").click(function () {
                            var ctr = $(this);
                            valid($('#' + ctr.attr("id").replace('_chooser', '')), ctr);
                        });
                        break;
                    case 'file': //选择list
                        $('#' + id + "_file").addClass("valid").change(function () {
                            var ctr = $(this);
                            valid(ctr, ctr);
                        });
                        break;
                }
            }
            else
                ctr.addClass("valid").blur(function () { valid($(this)); });
            if (options) {
                ctr.data("valid", options);
                if (options.group)
                    ctr.addClass(options.group)
            }
        });
        ///#endregion
    };

    ///#region 内部方法
    function valid(ctr, showctr) {
        var valid = ctr.data("valid"); //获取验证配置信息
        //        valid = (valid && valid.isNotEmpty()) ? $.parseJSON(valid) : {};

        if (valid) {
            var arrError = new Array;
            var value = ctr.val().trim();
            if (valid.required && value.length == 0)//非空判断
                arrError.push($iconst.validator.required)
            if (value.length > 0) {
                if (showctr) {//自定义控件验证
                    if (valid.range)
                        checkChooserRange(value, valid, arrError);
                }
                else {
                    var type = ctr.attr("itype") || valid.type;
                    if (type) {//非String格式
                        switch (type) {
                            case "int":
                                if (isInteger(value)) {
                                    if (valid.range)
                                        arrError = checkRange(value * 1, valid, arrError, $iconst.validator.numberRange);
                                }
                                else
                                    arrError.push($iconst.validator.integerRule);
                                break;
                            case "num":
                            case "cur":
                                var fraction = valid.fraction || iconfig.format.decimalfraction;
                                if (isFloat(value)) {
                                    if (valid.range)
                                        arrError = checkRange(value * 1, valid, arrError, $iconst.validator.numberRange);
                                }
                                else
                                    arrError.push($iconst.validator.numberRule.format(fraction))
                                break;
                            case "date":
                                value = value.toDate();
                                if (value) {
                                    if (valid.range)
                                        arrError = checkDateRange(value, valid, arrError);
                                }
                                else
                                    arrError.push($iconst.validator.dateRule);
                                break;
                            case "datetime":
                                value = value.toDateTime();
                                if (!value)
                                    arrError.push($iconst.validator.datetimeRule);
                                break;
                            case "bool":
                                break;
                        }
                    }
                    else {//String格式
                        if (valid.range)
                            arrError = checkRange(value.length, valid, arrError, $iconst.validator.textRange);

                        if (arrError.length == 0 && valid.rule) {//配置规则验证
                            if (ctr.attr('type') == 'file')//文件类型时转换为小写
                                value = getFileExtName(value).toLowerCase();
                            var rule = getJsonValue(iconfig.validator.rules, valid.rule);
                            if (rule && !regTest(rule, value))
                                arrError.push(getJsonValue($iconst.validator.rules, valid.rule))
                        }
                    }

                    if (arrError.length == 0 && valid.custrule && valid.custrule.length > 0 && valid.custrule[0] && !regTest(valid.custrule[0], value))//自定义规则验证
                        arrError.push(valid.custrule.length > 1 ? valid.custrule[1] : $iconst.validator.custrule);

                    if (arrError.length == 0 && valid.custfn && valid.custfn.length > 1 && !valid.custfn[0](ctr, value))//自定义方法验证
                        arrError.push(valid.custfn[1]);
                }
            }

            if (arrError.length > 0) {//生成验证信息
                bulidValidError(showctr || ctr, arrError);
                return false;
            }
            else
                closeValidError(showctr || ctr);
        }
        return true;
    }
    function checkRange(value, valid, arrerror, errortext) {
        var min = valid.range[0], max = valid.range[1];
        if (value < min || value > max)
            arrerror.push(errortext.format(min, max));
        return arrerror;
    }
    function checkDateRange(value, valid, arrerror) {
        if (valid.range.length > 0) {
            value = Date.parse(value)
            var min = toDateNum(valid.range[0]), max = toDateNum(valid.range[1]), result = true;
            if (min && value < min)
                result = false;
            else if (max && value > max)
                result = false;

            if (!result) {
                var msg = '';
                if (min)
                    msg = $iconst.validator.greatthan.format(valid.range[0]);
                if (max)
                    msg += (msg.length > 0 ? $iconst.validator.and : '') + $iconst.validator.lessthan.format(valid.range[1]);
                arrerror.push($iconst.validator.dateRange.format(msg));
            }
        }
        return arrerror;
    }
    function checkChooserRange(value, valid, arrerror) {
        if (valid.range.length > 0) {
            value = value.split(iconfig.common.valuesplit).length;
            var min = valid.range[0], max = valid.range[1], result = true;
            if (min && value < min)
                result = false;
            else if (max && value > max)
                result = false;

            if (!result) {
                var msg = '';
                if (min)
                    msg = $iconst.validator.greatthan.format(valid.range[0]);
                if (max)
                    msg += (msg.length > 0 ? $iconst.validator.and : '') + $iconst.validator.lessthan.format(valid.range[1]);
                arrerror.push($iconst.validator.ctrRange.format(msg));
            }
        }
        return arrerror;
    }
    function bulidValidError(ctr, errors) {
        if (errors && errors.length > 0) {
            var parent = ctr.parent();
            var errorpanel = parent.find('#' + ctr.attr('id') + '_validerror');
            if (errorpanel.length == 0) {
                errorpanel = $(document.createElement('div')).addClass("valid-error").attr('id', ctr.attr('id') + '_validerror');
                parent.append(errorpanel);
            }
            else
                errorpanel.html('');
            var sbError = new StringBuilder();

            var div = $(document.createElement('div')).addClass("valid-errortext");
            for (var i = 0; errors[i]; i++) {
                sbError.append('<div class="valid-errortext">').append(errors[i]).append("</div>");
                //                div.clone().text(errors[i]).appendTo(errorpanel);
            }
            errorpanel.html(sbError.toString());
            ictrcore.upTip(ctr, errorpanel, iconfig.validator.errorcss);
            errorpanel.show();
            sbError = null;
            errors = null;
        }
    }
    function closeValidError(ctr) {
        ctr.parent().find('#' + ctr.attr('id') + '_validerror').html('').remove();
    }
    ///#endregion

    $.validArea = function (selector, group) {
        var result = true;
        $((selector || '') + ' .valid' + (group ? '.' + group : '')).each(function () {
            var showctr, ctr = $(this), ctrtype = ctr.attr("ctr");
            if (ctrtype) {//自定义控件验证
                var id = ctr.attr('id');
                switch (ctrtype) {
                    case 'ddl': //下拉选择菜单
                        showctr = ctr;
                        ctr = $('#' + id.substring(0, id.length - 2));
                        break;
                    case 'list':
                        showctr = ctr;
                        ctr = $('#' + id.replace('_chooser', ''));
                        break;
                    case 'file':
                        showctr = ctr;
                        break;
                }
            }
            if (!valid(ctr, showctr) && result)
                result = false;
        });
        return result;
    }
})(jQuery);